package com.huawei.demo;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.core.region.Region;
import com.huaweicloud.sdk.dds.v3.DdsClient;
import com.huaweicloud.sdk.dds.v3.model.ListAuditlogLinksRequest;
import com.huaweicloud.sdk.dds.v3.model.ListAuditlogLinksResponse;
import com.huaweicloud.sdk.dds.v3.model.ListAuditlogsRequest;
import com.huaweicloud.sdk.dds.v3.model.ListAuditlogsResponse;
import com.huaweicloud.sdk.dds.v3.model.ProduceAuditlogLinksRequestBody;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AuditLogDownloadDemo {
    private static final Logger logger = LoggerFactory.getLogger(AuditLogDownloadDemo.class.getName());

    /**
     * args[0] = "<YOUR IAM_END_POINT>"
     * args[1] = "<YOUR END_POINT>"
     * args[2] = "<YOUR AK>"
     * args[3] = "<YOUR SK>"
     * args[4] = "<YOUR INSTANCE_ID>"
     * args[5] = "<YOUR REGION_ID>"
     * args[6] = "<YOUR START_TIME>"
     * args[7] = "<YOUR END_TIME>"
     * @param args
     */

    public static void main(String[] args) {
        if (args.length != 8) {
            logger.info("Illegal Arguments");
        }

        String iamEndpoint = args[0];
        String endpoint = args[1];

        String ak = args[2];
        String sk = args[3];

        String instanceId = args[4];
        String regionId = args[5];

        String startTime = args[6];
        String endTime = args[7];

        ICredential auth = new BasicCredentials()
                .withIamEndpoint(iamEndpoint)
                .withAk(ak)
                .withSk(sk);

        // 根据需要配置是否跳过SSL证书验证
        HttpConfig httpConfig = HttpConfig.getDefaultHttpConfig().withIgnoreSSLVerification(true);
        DdsClient client = DdsClient.newBuilder()
                .withCredential(auth)
                .withRegion(new Region(regionId, endpoint))
                .withHttpConfig(httpConfig)
                .build();
        //获取审计日志id列表，根据审计日志列表，查询审计日志下载链接
        List<String> ids = queryAuditLogIds(client, instanceId, startTime, endTime);
        getAuditLogLinks(client, ids, instanceId);
    }

    private static List<String> queryAuditLogIds(DdsClient client, String instanceId, String startTime, String endTime) {
        ListAuditlogsRequest request = new ListAuditlogsRequest();
        //设置实例id，起始时间，结束时间
        request.setInstanceId(instanceId);
        request.setStartTime(startTime);
        request.setEndTime(endTime);
        ListAuditlogsResponse response;
        List<String> ids = new ArrayList<>();
        //获取审计日志id列表
        try {
            response = client.listAuditlogs(request);
            logger.info(response.toString());
            for (int i = 0; i < response.getAuditLogs().size(); i++) {
                ids.add(response.getAuditLogs().get(i).getId());
            }
        } catch (ConnectionException e) {
            logger.error("ConnectionException", e);
        } catch (RequestTimeoutException e) {
            logger.error("RequestTimeoutException ", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(), e.getErrorMsg());
        }
        return ids;
    }

    private static void getAuditLogLinks(DdsClient client, List<String> ids, String instanceId) {
        ListAuditlogLinksRequest request = new ListAuditlogLinksRequest();
        ProduceAuditlogLinksRequestBody body = new ProduceAuditlogLinksRequestBody();
        body.setIds(ids);

        request.setInstanceId(instanceId);
        request.withBody(body);
        //获取审计日志下载链接
        try {
            ListAuditlogLinksResponse response = client.listAuditlogLinks(request);
            logger.info(response.toString());
        } catch (ConnectionException e) {
            logger.error("ConnectionException", e);
        } catch (RequestTimeoutException e) {
            logger.error("RequestTimeoutException ", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(), e.getErrorMsg());
        }
    }
}
